import { defineStore } from 'pinia'
import { ref, onBeforeUnmount } from 'vue'

export const useMenuStore = defineStore('useMenuStore', () => {
  // 使用 ref 创建响应式引用
  const selectedMenuIndex = ref(null) // 初始化选中的菜单项索引

  // 选择菜单项的函数
  const selectMenuItem = (index) => {
    selectedMenuIndex.value = index
    // 保存选中状态到 localStorage
    localStorage.setItem('selectedMenuIndex', index)
  }

  // 恢复选中菜单项的函数
  const restoreSelectedMenu = () => {
    // 从 localStorage 读取选中状态
    const selectedIndex = localStorage.getItem('selectedMenuIndex')
    console.log(selectedMenuIndex)
    if (selectedIndex !== null) {
      selectedMenuIndex.value = selectedIndex
    }
  }
  onBeforeUnmount(() => {
    localStorage.removeItem('selectedMenuIndex')
  })

  // 返回 store 的状态和函数
  return {
    selectedMenuIndex,
    selectMenuItem,
    restoreSelectedMenu
  }
})
